package guichatapplication;

import chatclient.ChatClient;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.DIRECTORIES_ONLY;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;

public class IndividualWindow extends javax.swing.JFrame {

    private ArrayList<String> lstFriendInGroup;
    private ArrayList<String> lstFriendOutGroup;
    private boolean isGroupChat;
    
    public IndividualWindow(String identify) {
        initComponents();

        this.btnRemove.setVisible(false);
        this.btnAddUser.setVisible(false);
        this.lstFriendInList.setVisible(false);
        this.lstFriendOutGroupList.setVisible(false);
        this.lstFriendInGroup = null;
        this.lstFriendOutGroup = null;
        this.isGroupChat = false;
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.identify = identify;      
        this.lbIdentify.setText(identify);
        this.messages = new ArrayList<>();
        
        lstMessage.setCellRenderer(new MessageListRenderer());
        this.resetJlistModel();        
    }
    
    // Use for group
    public IndividualWindow(String identify, ArrayList<String> lstFriend, ArrayList<String> lstFriengOutGroup) {
        initComponents();               
        
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.identify = identify;      
        this.lbIdentify.setText(identify);
        this.messages = new ArrayList<>();
        
        lstMessage.setCellRenderer(new MessageListRenderer());
        this.resetJlistModel();        
        
        this.lstFriendInGroup=lstFriend;
        this.lstFriendOutGroup=lstFriengOutGroup;
        this.isGroupChat = true;
        this.lstFriendInList.setModel(new javax.swing.AbstractListModel() {
            @Override
            public int getSize() {
                return lstFriendInGroup.size();
            }

            //public int getSize() { return models.length; }
            @Override
            public Object getElementAt(int i) {
                return lstFriendInGroup.get(i);
            }
            //public Object getElementAt(int i) { return models[i]; }
        });
        this.lstFriendOutGroupList.setModel(new javax.swing.AbstractListModel() {
            @Override
            public int getSize() {
                return lstFriendOutGroup.size();
            }

            //public int getSize() { return models.length; }
            @Override
            public Object getElementAt(int i) {
                return lstFriendOutGroup.get(i);
            }
            //public Object getElementAt(int i) { return models[i]; }
        });
    }

    // Receive Message
    public void addMessage(String message) {
        this.messages.add(new MessageListCell(-1, message));
        this.resetJlistModel();
    }

    // Add unread message from JList
    public void addMessage(ArrayList<MessageListCell> lst) {
        for (int i = 0; i < lst.size(); i++) {
            this.messages.add(lst.get(i));
        }
        this.resetJlistModel();
    }

    public void resetJlistModel() {
        this.lstMessage.setModel(new javax.swing.AbstractListModel() {
            @Override
            public int getSize() {
                return messages.size();
            }

            //public int getSize() { return models.length; }
            @Override
            public Object getElementAt(int i) {
                return messages.get(i);
            }
            //public Object getElementAt(int i) { return models[i]; }
        });
        
        if (this.lstFriendInGroup != null && this.lstFriendInList != null) {
            this.lstFriendInList.setModel(new javax.swing.AbstractListModel() {
                @Override
                public int getSize() {
                    return lstFriendInGroup.size();
                }

                //public int getSize() { return models.length; }
                @Override
                public Object getElementAt(int i) {
                    return lstFriendInGroup.get(i);
                }
                //public Object getElementAt(int i) { return models[i]; }
            });
        }
        if (this.lstFriendOutGroup != null && this.lstFriendOutGroupList != null) {
            this.lstFriendOutGroupList.setModel(new javax.swing.AbstractListModel() {
                @Override
                public int getSize() {
                    return lstFriendOutGroup.size();
                }

                //public int getSize() { return models.length; }
                @Override
                public Object getElementAt(int i) {
                    return lstFriendOutGroup.get(i);
                }
                //public Object getElementAt(int i) { return models[i]; }
            });
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstMessage = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        lbIdentify = new javax.swing.JLabel();
        tbNewMessage = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstFriendInList = new javax.swing.JList();
        btnRemove = new javax.swing.JButton();
        btnAddUser = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        lstFriendOutGroupList = new javax.swing.JList();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(lstMessage);

        jLabel1.setText("Identify");

        lbIdentify.setText("jLabel4");

        tbNewMessage.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbNewMessagePress(evt);
            }
        });

        jButton1.setText("File...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(lstFriendInList);

        btnRemove.setText("Remove User");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        btnAddUser.setText("Add User");
        btnAddUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddUserActionPerformed(evt);
            }
        });

        jScrollPane4.setViewportView(lstFriendOutGroupList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(lbIdentify, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(92, 92, 92)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(btnRemove)))
                        .addGap(9, 9, 9))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnAddUser, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tbNewMessage)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(lbIdentify))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemove)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAddUser)
                        .addGap(5, 5, 5))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addGap(18, 18, 18)
                        .addComponent(tbNewMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tbNewMessagePress(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbNewMessagePress
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            // Add new Right Message. This is my message, not my chat friend
            this.messages.add(new MessageListCell(1, this.tbNewMessage.getText()));
            //this.messages.add(new MessageListCell(1, this.identify+":" + this.tbNewMessage.getText()));
            if (this.isGroupChat == false) {
                ChatClient.getInstance().sendMessage(this.identify, this.tbNewMessage.getText());
            } else {
                ChatClient.getInstance().sendMessageToGroup(this.identify, this.tbNewMessage.getText());
            }
            this.resetJlistModel();
            this.tbNewMessage.setText("");
            // Scrollbar to the end

        }
    }//GEN-LAST:event_tbNewMessagePress

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fileChooser=new JFileChooser();
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.showOpenDialog(this);
        //fileChooser.setFileSelectionMode(DIRECTORIES_ONLY);
        //fileChooser.showSaveDialog(this);
        File file=fileChooser.getSelectedFile();
        if(file!=null){
            if (this.isGroupChat == false) {
                ChatClient.getInstance().wantSendFile(this.identify, file.getPath());
            } else {
                ChatClient.getInstance().wantSendFileToGroup(this.identify, file.getPath());
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        int index=this.lstFriendInList.getSelectedIndex();
        if(index!=-1) {
            //this.lstFriendInList.remove(index);
            String username = this.lstFriendInList.getSelectedValue().toString();
            ChatClient.getInstance().removeFromGroup(this.identify, username);
            this.lstFriendInGroup.remove(username);
            this.lstFriendOutGroup.add(username);
            this.resetJlistModel();
        }
        System.out.println("Remove user!, View should change. If view doesn't change, of course, bug!");
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddUserActionPerformed
        //System.out.println("Add user! as remove user");
        int index=this.lstFriendOutGroupList.getSelectedIndex();
        if(index!=-1) {
            //this.lstFriendInList.remove(index);
            String username = this.lstFriendOutGroupList.getSelectedValue().toString();
            ChatClient.getInstance().addUserToGroup(this.identify, username);
            this.lstFriendOutGroup.remove(username);
            this.lstFriendInGroup.add(username);
            this.resetJlistModel();
        }
    }//GEN-LAST:event_btnAddUserActionPerformed
    
    private ArrayList<MessageListCell> messages;

    public String identify;
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddUser;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JLabel lbIdentify;
    private javax.swing.JList lstFriendInList;
    private javax.swing.JList lstFriendOutGroupList;
    private javax.swing.JList lstMessage;
    private javax.swing.JTextField tbNewMessage;
    // End of variables declaration//GEN-END:variables
}
